﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Solidi
{
	public class DependencyRegistry : IDependencyRegistry
	{
		private static readonly IDependency[] Empty = new IDependency[0];

		private ConcurrentDictionary<IDependencyKey, DependencyGroup> _dependencies = new ConcurrentDictionary<IDependencyKey, DependencyGroup>();

		public void Add(IDependencyKey key, IDependency dependency)
		{
			DependencyGroup group = _dependencies.GetOrAdd(key, new DependencyGroup());

			group.Add(dependency);
		}

		public void Remove(IDependencyKey key, IDependency dependency)
		{
			DependencyGroup group;

			if (_dependencies.TryGetValue(key, out group))
			{
				group.Remove(dependency);
			}
		}

		public IDependency[] Find(IDependencyKey key)
		{
			DependencyGroup group;

			if (_dependencies.TryGetValue(key, out group))
			{
				return group.Dependencies;
			}

			return Empty;
		}

		public IEnumerable<IDependency> Dependencies
		{
			get
			{
				return _dependencies.SelectMany(e => e.Value.Dependencies);
			}
		}
	}
}
